package storageplugin

import (
	"fmt"
	"kubeInstall/pkg/client/db"
	"kubeInstall/server/models/storageplugin"
	"kubeInstall/utils/uuid"
)

func GetStoragePluginNFS(nfsId string) (*storageplugin.StorageNFS, error) {
	var nfs storageplugin.StorageNFS

	err := db.Db.Where("nfs_id = ?", nfsId).First(&nfs).Error

	if err != nil {
		if err == db.ErrRecordNotFound {
			return nil, fmt.Errorf("nfs ID %s not found", nfsId)
		}
		return nil, err
	}

	return &nfs, nil

}

func GetStoragePluginNFSByClusterId(clusterId string) (*storageplugin.StorageNFS, error) {
	var nfs storageplugin.StorageNFS

	err := db.Db.Select("*").Where("cluster_id = ?&& used = true", clusterId).Find(&nfs).Error

	if err != nil {
		return nil, err
	}

	return &nfs, nil
}

func UpdateStoragePluginNFSByClusterId(nfsId, clusterId string) error {

	err := db.Db.Model(&storageplugin.StorageNFS{}).Where("nfs_id = ?", nfsId).Updates(map[string]interface{}{"cluster_id": clusterId, "used": true}).Error
	if err != nil {
		return err
	}

	return nil
}

func ListStoragePluginNFS() ([]*storageplugin.StorageNFS, error) {
	var nfs []*storageplugin.StorageNFS

	err := db.Db.Select("*").Find(&nfs).Error
	if err != nil && err != db.ErrRecordNotFound {
		return nil, err
	}

	return nfs, nil
}

func CheckNfsServerStatus(ip string) bool {

	return true
}

func CheckNfsServerIpIsExist(ip string) bool {

	var count int
	db.Db.Model(storageplugin.StorageNFS{}).Where("nfs_server_ip = ?", ip).Count(&count)

	if count > 0 {
		return true
	}

	return false
}

func CheckNfsIdIsValid(nfsId string) bool {
	var count int

	db.Db.Model(storageplugin.StorageNFS{}).Where("nfs_id = ?", nfsId).Count(&count)
	if count > 0 {
		return true
	}

	return false
}
func CheckNfsIdIsUsed(nfsId string) bool {
	var count int

	db.Db.Model(storageplugin.StorageNFS{}).Where("nfs_id = ? && used = true", nfsId).Count(&count)
	if count > 0 {
		return true
	}

	return false
}

func AddStoragePluginNFS(nfs *storageplugin.StorageNFS) (*storageplugin.StorageNFS, error) {

	nfs.ID = uuid.GenUUID()

	if err := db.Db.Create(&nfs).Error; err != nil {
		return nil, err
	}
	return nfs, nil

}

func DeleteStoragePluginNFS(nfsId string) error {

	if err := db.Db.Delete(storageplugin.StorageNFS{ID: nfsId}).Error; err != nil {
		return err
	}
	return nil
}

func UpdateStoragePluginNFS(nfsId string, nfs *storageplugin.StorageNFS) error {

	if err := db.Db.Model(&storageplugin.StorageNFS{}).Where("nfs_id = ?", nfsId).Update(&nfs).Error; err != nil {
		return err
	}

	return nil
}
